package com.dragonlance;

import java.nio.charset.CharacterCodingException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;

import org.apache.mina.core.session.IoSession;

import com.dragonlance.net.DLOutProtocolNumber;
import com.dragonlance.net.PackageIn;
import com.dragonlance.net.PackageOut;
import com.dragonlance.thread.LoginThread;

public class ClientMgr{
	private HashMap<Long, DLClient> clients;
	public ClientMgr() {
		clients = new HashMap<Long, DLClient>();
	}
	
	public void add(DLClient client){
		if(clients.containsKey(client.getUserId()))
		{
			DLClient temp = clients.get(client.getUserId());
			temp.disconnect();
		}
		clients.put(client.getUserId(), client);
	}
	
	public void remove(DLClient client){
		clients.remove(client.getUserId());
	}
	
	public DLClient remove(long sessionId){
		Iterator<Entry<Long, DLClient>> iter = clients.entrySet().iterator();
		while(iter.hasNext()){
			Map.Entry<Long, DLClient> entry = iter.next();
			DLClient client = entry.getValue();
			if(client.getId() == sessionId){
				remove(client);
				return client;
			}
		}
		return null;
	}
	
	public DLClient getClient(long sessionId){
		Iterator<Entry<Long, DLClient>> iter = clients.entrySet().iterator();
		while(iter.hasNext()){
			Map.Entry<Long, DLClient> entry = iter.next();
			DLClient client = entry.getValue();
			if(client.getId() == sessionId){
				return client;
			}
		}
		return null;
	}
	
	/**
	 * @param message 要发送的系统消息内容
	 * @param type 消息的类型
	 * @throws CharacterCodingException 
	 */
	public void sendSystemMsgToAll(String message,int type) throws CharacterCodingException{
		PackageOut pkg = new PackageOut(DLOutProtocolNumber.SYSTEM_MESSAGE,1);
		pkg.writeUtf(message);
		sendToAll(pkg);
	}
	
	public void sendChatToAll(String message,String sender,int type) throws CharacterCodingException{
		PackageOut pkg = new PackageOut(DLOutProtocolNumber.CHAT,1);
		pkg.writeUtf(sender);
		pkg.writeUtf(message);
		sendToAll(pkg);
	}
	
	public void sendToAll(PackageOut pkg){
		Iterator<Entry<Long, DLClient>> iter = clients.entrySet().iterator();
		while(iter.hasNext()){
			Map.Entry<Long, DLClient> entry = iter.next();
			DLClient client = entry.getValue();
			client.out.sendPkg(pkg);
		}
	}

	public void loginClient(PackageIn pkg,IoSession session) {
		Thread login = new Thread(new LoginThread(pkg, session));
		login.start();
	}
}
